package com.czk.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

import javax.net.ssl.SSLException;
import java.io.File;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/5/8 10:16
 */
public class NettySever {
    public static void main(String[] args) throws SSLException {
        new NettySever().bind(7397);
    }

    private void bind(int port) throws SSLException {
        // 引入SSL安全验证
        File certChainFile = new File("F:\\IdeaProjects\\netty\\netty-ssl\\src\\main\\java\\com\\czk\\ssl\\server\\server.crt");
        File keyFile = new File("F:\\IdeaProjects\\netty\\netty-ssl\\src\\main\\java\\com\\czk\\ssl\\server\\pkcs8_server.key");
        File rootFile = new File("F:\\IdeaProjects\\netty\\netty-ssl\\src\\main\\java\\com\\czk\\ssl\\server\\ca.crt");
        SslContext sslContext = SslContextBuilder.forServer(certChainFile, keyFile).trustManager(rootFile).clientAuth(ClientAuth.REQUIRE).build();
        // 配置线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 启动
            bootstrap.group(bossGroup, workGroup)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new MyServerInitializer(sslContext));
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            System.out.println("服务器启动成功");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
